<template>
  <div class="attendance">
    <div class="attendance-search">
      <el-select v-model="queryParamsTeam.pointsId" placeholder="请选择" size="small" class="mr10"
                 v-if="type!=='pointDetail'">
        <el-option
          v-for="item in postList"
          :key="item.id"
          :label="item.name"
          :value="item.id">
        </el-option>
      </el-select>
      <el-date-picker
        v-model="monthThis"
        size="small"
        type="month"
        format="yyyy-MM"
        value-format="yyyy-MM"
        placeholder="选择月">
      </el-date-picker>
      <el-button
        class="ml10"
        type="primary"
        icon="el-icon-search"
        size="small"
        @click="handleQuery"
      >搜索
      </el-button>
      <!--      <el-button icon="el-icon-refresh" size="small" @click="resetQuery"-->
      <!--      >重置-->
      <!--      </el-button-->
      <!--      >-->
    </div>
    <div class="attendance-body mt10">
      <div class="attendance-box">
        <div class="attendance-box-thead" :style="{'width': `${dayMonth.length*70}px`}">
          <div class="attendance-box-th" v-for="item in dayMonth">
            <span>周{{ item.week }}</span>
            <span>{{ item.dayOne }}</span>
          </div>
        </div>
        <div v-for="(projectitem,projectindex) in projectPostList" :key="projectindex">
          <div class="projectitem-title" :style="{'width': `${dayMonth.length*70}px`}">
            {{ projectitem.name }}
          </div>
          <div class="attendance-box-tdbox" :style="{'width': `${dayMonth.length*70}px`}">
            <div class="attendance-box-tdLine" v-for="item in dayMonth">
              <template v-if="dayName[item.dayName]">
                <template v-for="user in dayName[item.dayName][projectitem.id]">
                  <div class="attendance-box-tdLine-box user-work"
                       @click="showDayLog(user,teamlist[user.userId], item.dayName, item)" v-if="user.cateId">
                    {{ teamlist[user.userId] ? teamlist[user.userId].nickName : '未知' }}
                  </div>
                  <div v-else class="attendance-box-tdLine-box user-work-rest">
                    {{ teamlist[user.userId] ? teamlist[user.userId].nickName+'(休)' : '未知' }}
                  </div>
                </template>
                <div class="attendance-box-tdLine-box not-woek"
                     v-if="JSON.stringify(dayName[item.dayName][projectitem.id])=='{}'">
                  未排班
                </div>
              </template>
              <template v-else>
                <div class="attendance-box-tdLine-box not-woek">
                  未排班
                </div>
              </template>
            </div>
          </div>
        </div>
      </div>
    </div>
    <attendDetail :visible.sync="attenVisible" type="point" :userId="userId" :pointsId="queryParamsTeam.pointsId"
                  :attendLog="attendLog" :pointsData="pointsData"></attendDetail>
  </div>
</template>

<script>
import {listStagnationPointUser} from "@/api/system/stagnation_point";
import {listScheduling} from "@/api/system/sign_category";
import {
  listStagnationPoint
} from "@/api/system/stagnation_point";
import attendDetail from "@/views/system/sign_category/components/attendDetail";
import {
  getProject
} from "@/api/system/project";

export default {
  name: "pointLine",
  components: {attendDetail},
  props: ['type', 'pointData'],
  data() {
    return {
      value: '',
      monthThis: '',
      dayMonth: [],
      queryParamsTeam: {
        pageNum: 1,
        pageSize: 200,
        pointsId: ''
      },
      chooseWork: {},
      teamlist: {}, // 驻点人员
      dayName: {}, // 当月排班记录
      postList: [],
      attenVisible: false,
      userId: 0,
      attendLog: null,
      pointsData: null,
      projectId: 0,
      projectPostList: []
    }
  },
  watch: {
    pointData() {
      // 获取执勤点队员
      this.initFn()
    }
  },
  created() {
    let tiem_ = this.newDate().split('-')
    this.monthThis = tiem_.join('-')
    this.getDaysOfWeek(tiem_[0], tiem_[1])
    // // 需要岗位
    this.initFn()
  },
  methods: {
    initFn() {
      // type pointDetail 从执勤点进入
      if (this.type == 'pointDetail') {
        this.queryParamsTeam.pointsId = this.pointData ? this.pointData.id : ''
      }
      // 如果从驻点详情进入不需要请求驻点列表
      if (this.type !== 'pointDetail') {
        // 从驻点考勤记录进入
        this.getPostsList() // 查询驻点
      }
      if (this.type == 'pointDetail') {
        this.projectId = this.pointData.projectId
        this.getProjectData()
      }
      this.getTeamList() // 执勤点团队
      this.leaveOption()
    },
    showDayLog(item, user, dayName, data) {
      // item 用户id user 用户信息
      // const year = String(dayName).slice(0, 4);
      // const month = String(dayName).slice(4, 6);
      // const day = String(dayName).slice(6, 8);
      // this.attendLog = this.$deepCopy({
      //   dayName: `${year}-${month}-${day}`
      // })
      item.dayName = data.day
      this.attendLog = this.$deepCopy(item)
      this.userId = item.userId
      for (let item of this.postList) {
        if (item.id == this.queryParamsTeam.pointsId) {
          this.pointsData = this.$deepCopy(item)
        }
      }
      this.attenVisible = true
    },
    /** 查询驻点列表 */
    getPostsList() {
      listStagnationPoint(this.queryParams).then(response => {
        if(response.rows.length){
          this.queryParamsTeam.pointsId = response.rows[0].id
          this.projectId = response.rows[0].projectId
          this.postList = response.rows;
          this.getProjectData()
        }
        this.handleQuery()
      });
    },
    getProjectData() {
      getProject(this.projectId).then(res => {
        this.projectPostList = res.data.detail.projectPostList
        this.getTeamList() // 驻点团队
        this.listSchedulingFn() // 当月执勤点所有排班记录
      })
    },
    // 执勤点团队
    getTeamList() {
      listStagnationPointUser(this.queryParamsTeam).then(response => {
        let a_ = {}
        for (let item of response.rows) {
          a_[item.userId] = item
        }
        this.teamlist = this.$deepCopy(a_);
      });
    },
    /** 当月执勤点所有排班记录 */
    listSchedulingFn(userId) {
      let that = this
      this.$modal.loading("正在查询中，请稍候...");
      let data_ = {
        pageNum: 1,
        pageSize: 3000,
        pointsId: this.queryParamsTeam.pointsId, //  驻点
        month: this.monthThis.split('-').join(''), // 月份
      }
      if (userId) {
        data_.userId = userId
      }
      listScheduling(data_).then(res => {
        let day_ = {}
        for (let item of res.rows) {
          if (!day_[item.day]) {
            day_[item.day] = {}
          }
          for (let project of this.projectPostList) {
            if (!day_[item.day][project.id]) {
              day_[item.day][project.id] = {}
            }
            if (item.postId == project.id) {
              day_[item.day][project.id][item.userId] = item
            }
          }
        }
        this.dayName = this.$deepCopy(day_)
        setTimeout(() => {
          that.$modal.closeLoading();
        }, 500)
      }).catch(res => {
        setTimeout(() => {
          that.$modal.closeLoading();
        }, 500)
      })
    },
    getDaysOfWeek(year, month) {
      let week = ['日', '一', '二', '三', '四', '五', '六']
      let dayMonth = []
      let d = new Date(year, month, 0)
      let day = d.getDate();
      this.widthTable = day * 60 + 100
      let firstDayOfMonth = new Date(year, month - 1, 1)
      //该月第一天是周几?0表示周日，1表示周一...6表示周六
      let dayWeek = firstDayOfMonth.getDay()
      for (let i = 0; i < day; i++) {
        dayMonth.push({
          day: `${year}-${month}-${i + 1}`,
          dayOne: i + 1,
          week: week[dayWeek],
          dayName: `${year}${month}${(i + 1) < 10 ? '0' + (i + 1) : (i + 1)}`
        })
        dayWeek++
        if (dayWeek > 6) {
          dayWeek = 0
        }
      }
      this.dayMonth = dayMonth
    },
    /** 搜索按钮操作 */
    handleQuery() {
      for (let item of this.postList) {
        if (this.queryParamsTeam.pointsId == item.id) {
          this.projectId = item.projectId
        }
      }
      this.dayName = {}
      this.teamlist = {}
      this.getProjectData()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    newDate() {
      let date = new Date()
      let y = date.getFullYear()
      let m = date.getMonth() + 1
      m = m < 10 ? '0' + m : m
      return y + '-' + m
    },
    leaveOption(){
      // 获取请假人员
    }
  }
}
</script>

<style scoped>
.attendance-body {
  overflow-x: auto;
}

.attendance-box-thead {
  display: flex;
  font-size: 12px;
  text-align: center;
  border: 1px solid #f4f4f4;
  padding: 5px 0;
  box-shadow: 0 0 6px #ddd;
}

.attendance-box-th {
  display: flex;
  flex-direction: column;
  width: 70px;
}

.attendance-box-tdbox {
  overflow-x: auto;
  display: flex;
  min-height: 100px;
  border: 1px solid #f4f4f4;
}

.attendance-box-tdLine {
  width: 70px;
  text-align: center;
  font-size: 12px;
  border-right: 1px solid #f4f4f4;
  padding-top: 10px;
}

.attendance-box-tdLine:last-child {
  border-right: 0;
}

.attendance-box-tdLine-box {
  padding: 5px 0;
  cursor: pointer;
  margin: 0 2px;
}

.attendance-box-tdLine-box:hover {
  background: #f4f4f4;
  color: #333;
}

.user-work {
  color: #fff;
  background: #5cba33;
  margin-bottom: 3px;
  border-radius: 2px;
}
.user-work-rest{
  background: #ddd;
  margin-bottom: 3px;
  border-radius: 2px;
  color: #999;
}
.not-woek {
  color: #ff1414;
}

.projectitem-title {
  background: #f4f4f4;
  padding: 10px;
  font-size: 14px;
}
</style>
